from io import BytesIO

from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse
from django.db.models import Q
from django.views.generic import View
from apps.cms_user import models

from django.contrib.auth import authenticate, login, logout  # dj自带认证系统
# Create your views here.
from utils.loginMixin.mixin import LoginRequiredMixin
class IndexView(LoginRequiredMixin,View):
    def get(self, request):
        print(request.user)
        return render(request, 'layout/base.html',{"user":request.user})


# 处理登陆逻辑
class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        username = request.POST.get("username", None)
        password = request.POST.get("password", None)
        captcha = request.POST.get("captcha", None)
        web_code = self.request.session.get("image_code")  # 后台的验证码
        if not all([username, password, captcha]):
            return render(request, 'login.html', {"errmsg": "输入信息不完整"})
        if captcha.strip().upper() != web_code:
            return render(request, 'login.html', {"errmsg": "验证码错误"})
        if not web_code:
            return render(request, 'login.html', {"errmsg": "验证码已经过期"})
        user = authenticate(username=username, password=password)
        if user is not None:
            print("用户名密码正确",username,password)
            login(request, user)  # 记住登陆状态
            # 这里要重定向到指定地址
            next_url = request.GET.get('next', reverse('cms:index')) # 如果有nexturl 则跳转到next_url 否认默认跳转首页
            print(next_url)
            response = redirect(next_url)  # HttpResponseRedirect
            response.set_cookie('username', username, 7 * 24 * 3600)
            return response
        else:
            return render(request, 'login.html', {"errmsg": "用户名或密码错误"})


# 显示图片验证码
class GetCheckImage(View):
    '''生成图片二维码'''
    def get(self, request):
        from utils.check_img.checkimg import check_code
        image_obj, code = check_code()
        # 把验证码加入到session中
        request.session["image_code"] = code
        request.session.set_expiry(60)  # 设置60秒过期时间
        # 把图片写到内存中
        stream = BytesIO()
        image_obj.save(stream, 'png')
        return HttpResponse(stream.getvalue())

class LogoutView(View):
    def get(self,request):
        request.session['user_id'] = None
        return redirect(reverse("cms:login"))

